//
//  TestWordChooseCourseViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/6.
//

#import "TestWordChooseCourseViewController.h"
#import "TestWordChooseCourseCell.h"
#import "CourseChooseFinishViewController.h"
#import "WordTestSetView.h"
#import "CourseListManager.h"
#import "CourseListModel.h"
#import "WordTestOldDataAlertView.h"
#import "CheckCourseLastTestManager.h"
#import "LastCourseTestModel.h"
#import "SaveCourseTestSetManager.h"
#import "EditUserInfoManager.h"
#import "WordTestSaveAlertView.h"
#import "MyCollectionListCell.h"
#import <AVFoundation/AVFoundation.h>
#import "CourseTestWordListManager.h"
#import "TestWordViewController.h"
#import "JPNavigationController.h"
#import "WordTestDeleteProgressManager.h"
#import "nuisdk/NeoNuiTts.h"
#import "AudioController.h"
#import <AdSupport/ASIdentifierManager.h>
#import "GetALiYunTokenManager.h"
#import "NeoNuiTtsManager.h"
#import "WordDetialViewController.h"
#import "JPNavigationController.h"

@interface TestWordChooseCourseViewController()<
UITableViewDelegate,
UITableViewDataSource,
JPAPIManagerCallBackDelegate,
///AVSpeechSynthesizerDelegate,
ConvVoiceRecorderDelegate,
NeoNuiTtsDelegate
>

@property(nonatomic,strong)UIButton *courseBtn;
@property(nonatomic,strong)UIButton *errorBtn;
@property(nonatomic,strong)UIButton *testBtn;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIButton *allSelBtn;
@property(nonatomic,strong)WordTestSetView *setView;
@property(nonatomic,strong)CourseListManager *listManager;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)NSMutableArray *selArr;
@property(nonatomic,strong)WordTestOldDataAlertView *oldDataAlertView;
@property(nonatomic,strong)CheckCourseLastTestManager *lastTestManager;
@property(nonatomic,strong)LastCourseTestModel *lastCourseTestModel;
@property(nonatomic,strong)SaveCourseTestSetManager *chooseCourseManager;
@property(nonatomic,strong)EditUserInfoManager *editUserInfoManager;
@property(nonatomic,assign)BOOL isBack;//是否是返回的时候请求的
@property(nonatomic,strong)WordTestSaveAlertView *saveAlertView;
@property(nonatomic,strong)UITableView *errorTableView;
@property(nonatomic,strong)NSMutableArray *errorDataArr;
@property(nonatomic,strong)UIButton *sureBtn;
@property(nonatomic,strong)MyCollectionListCell *currentCell;
@property(nonatomic,assign)NSInteger playIndex;
//@property(nonatomic,strong)AVSpeechSynthesizer *synthesizer;
@property(nonatomic,strong)CourseTestWordListManager *wordListManager;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,strong)WordTestDeleteProgressManager *deleteProgressManager;
@property(nonatomic,assign)BOOL isFirst;
@property(nonatomic,assign)BOOL isUpdateErrorData;
@property(nonatomic,strong)NeoNuiTts *nui;
@property(nonatomic,strong)AudioController *audioController;
@property (nonatomic, strong) dispatch_queue_t work_queue;
@property(nonatomic,strong)GetALiYunTokenManager *aLiYunTokenManager;
@property(nonatomic,strong)AVPlayer *avPlayer;
@property (nonatomic,assign)BOOL isPlaying;

@end

@implementation TestWordChooseCourseViewController

-(CourseListManager *)listManager{
    if(!_listManager){
        _listManager = [[CourseListManager alloc]init];
        _listManager.delegate = self;
    }
    return _listManager;
}

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(NSMutableArray *)selArr{
    if(!_selArr){
        _selArr = [NSMutableArray array];
    }
    return _selArr;
}

-(CheckCourseLastTestManager *)lastTestManager{
    if(!_lastTestManager){
        _lastTestManager = [[CheckCourseLastTestManager alloc]init];
        _lastTestManager.delegate = self;
    }
    return _lastTestManager;
}

-(SaveCourseTestSetManager *)chooseCourseManager{
    if(!_chooseCourseManager){
        _chooseCourseManager = [[SaveCourseTestSetManager alloc]init];
        _chooseCourseManager.delegate = self;
    }
    return _chooseCourseManager;
}

-(EditUserInfoManager *)editUserInfoManager{
    if(!_editUserInfoManager){
        _editUserInfoManager = [[EditUserInfoManager alloc]init];
        _editUserInfoManager.delegate = self;
    }
    return _editUserInfoManager;
}

-(NSMutableArray *)errorDataArr{
    if(!_errorDataArr){
        _errorDataArr = [NSMutableArray array];
    }
    return _errorDataArr;
}

-(CourseTestWordListManager *)wordListManager{
    if(!_wordListManager){
        _wordListManager = [[CourseTestWordListManager alloc]init];
        _wordListManager.delegate = self;
    }
    return _wordListManager;
}

-(WordTestDeleteProgressManager *)deleteProgressManager{
    if(!_deleteProgressManager){
        _deleteProgressManager = [[WordTestDeleteProgressManager alloc]init];
        _deleteProgressManager.delegate = self;
    }
    return _deleteProgressManager;
}

-(GetALiYunTokenManager *)aLiYunTokenManager{
    if(!_aLiYunTokenManager){
        _aLiYunTokenManager = [[GetALiYunTokenManager alloc]init];
        _aLiYunTokenManager.delegate = self;
    }
    return _aLiYunTokenManager;
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self popGestureClose];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self popGestureOpen];
}

#pragma mark - 返回
- (void)defaultBackSet{
    [self.customNavigationBar setLeftItemWithIcon:[UIImage imageNamed:@"nav_back_logo"]];
    [self.customNavigationBar.leftButton addTarget:self action:@selector(__backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)__backButtonClicked:(UIButton*)btn{
    self.isBack = YES;
    self.lastTestManager.bookId = self.bookListModel.bookId;
    [self.lastTestManager loadData];
}

#pragma mark - 是否保留测试数据
-(void)showSaveAlertView{
    if(!self.saveAlertView){
        self.saveAlertView = [[WordTestSaveAlertView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,self.currentAvailableHeight)];
    }
    if(KEY_WINDOW){
        self.saveAlertView.model = self.lastCourseTestModel;
        [KEY_WINDOW addSubview:self.saveAlertView];
        __weak typeof(self)weakSelf = self;
        [self.saveAlertView setClickBlock:^(BOOL isYes) {
            [weakSelf.saveAlertView removeFromSuperview];
            if(isYes == NO){
                //不保留
                [weakSelf deleteProgress];
            }else{
                //保留
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.playIndex = -1;
    self.page = 1;
    
    [self createUI];
    //课程
    [self loadData];
    self.isFirst = YES;
    //检查进度
    [self checkData];
    
    [self initPlay];
    [self NuiTtsInit];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateErrorWord) name:@"UpdateErrorWord" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(wordDetialCollectRefresh:) name:@"WordDetialCollectRefresh" object:nil];
    
    //听力播放结束
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playToEndTime:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

#pragma mark - 单词详情改变了收藏状态
-(void)wordDetialCollectRefresh:(NSNotification*)notifi{
    if(notifi.object){
        WordListModel *model = notifi.object;
        for(NSInteger i = 0;i < self.errorDataArr.count;i++){
            WordListModel *model2 = self.errorDataArr[i];
            if([model.wordId isEqualToString:model2.wordId]){
                model2.isCollect = model.isCollect;
                [self.errorDataArr replaceObjectAtIndex:i withObject:model2];
                break;
            }
        }
        [self.errorTableView reloadData];
    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 重新设置 delegate 确保回调正常工作
    if (self.nui){
        self.nui.delegate = self;
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    
    if(self.avPlayer&&self.isPlaying == YES){
        [self.avPlayer pause];
        self.isPlaying = NO;
    }
    
}


#pragma mark - 语音合成播放需要
-(void)initPlay{
    
    self.audioController = [[AudioController alloc] init:only_player];
    self.audioController.delegate = self;
    [self.audioController setPlayerSampleRate:16000];// 16000返回音频的采样率
    
    self.work_queue = dispatch_queue_create("TestWordChooseCourseViewController_WorkQueue", DISPATCH_QUEUE_CONCURRENT);
    
}

#pragma mark - 语音合成初始化
-(void)NuiTtsInit{
    if (self.nui == NULL||self.nui == nil) {
        self.nui = [NeoNuiTtsManager sharedManager].nui;
        self.nui.delegate = self;
    }
    //请注意此处的参数配置，其中账号相关需要按照genInitParams的说明填入后才可访问服务
    NSString * initParam = [self genInitParams];
    int retcode = [self.nui nui_tts_initialize:[initParam UTF8String] logLevel:LOG_LEVEL_VERBOSE saveLog:YES];
    
    NSString *fontName = @"tomoka";
    [self.nui nui_tts_set_param:"font_name" value:[fontName UTF8String]];
    //在线合成
    [self.nui nui_tts_set_param:"mode_type" value:"2"]; // 必填
    NSString *speed_level = @"1";
    [self.nui nui_tts_set_param:"speed_level" value:[speed_level UTF8String]];
    NSString *pitch_level = @"0";
    [self.nui nui_tts_set_param:"pitch_level" value:[pitch_level UTF8String]];
    NSString *volume = @"2";
    [self.nui nui_tts_set_param:"volume)" value:[volume UTF8String]];
    // 字级别音素边界功能开关，该参数只对支持字级别音素边界接口的发音人有效。“1”表示打开，“0”表示关闭。
    [self.nui nui_tts_set_param:"enable_subtitle" value:"1"];
    
    if (retcode != 0) {
         TLog(@"init failed.retcode:%d", retcode);
         return;
    }
    
}

-(NSString *)genInitParams{
    NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
    NSString *bundlePath = [[NSBundle bundleWithPath:strResourcesBundle] resourcePath];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"voices"];
    // 创建目录
    BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        TLog(@"文件夹创建成功");
    }else{
        TLog(@"文件夹创建失败");
    }
    NSString *debug_path = testDirectory;
    NSMutableDictionary *ticketJsonDict = [NSMutableDictionary dictionary];
    [ticketJsonDict setObject:ALIYUNYUYINKEY forKey:@"app_key"];
    [self checkToken];
    NSString *TOKEN = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(!TOKEN){
        TOKEN = @"";
    }
    [ticketJsonDict setObject:TOKEN forKey:@"token"];
    
    //工作目录路径，SDK从该路径读取配置文件
    [ticketJsonDict setObject:bundlePath forKey:@"workspace"]; // 必填, 且需要有读写权限
//    TLog(@"workspace:%@", bundlePath);
    [ticketJsonDict setObject:debug_path forKey:@"debug_path"];
//    TLog(@"debug_path:%@", debug_path);

    [ticketJsonDict setObject:@"wss://nls-gateway.aliyuncs.com/ws/v1" forKey:@"url"]; // 默认

    // 设置成在线语音合成模式, 这个设置很重要, 遗漏会导致无法运行
    [ticketJsonDict setObject:@"2" forKey:@"mode_type"]; // 必填
    
    NSString *id_string = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//    TLog(@"id: %s", [id_string UTF8String]);
    [ticketJsonDict setObject:id_string forKey:@"device_id"]; // 必填, 推荐填入具有唯一性的id, 方便定位问题

    NSData *data = [NSJSONSerialization dataWithJSONObject:ticketJsonDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

#pragma mark - 获取token
-(void)checkToken{
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_TOKEN"];
    if(token){
        //token 存在 判断时间
        NSString *expireTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"ALIYUN_YUYIN_EXPIRETIME"];
        if(expireTime){
            NSDate *currentDate = [NSDate date];
            NSTimeInterval expireTimeInterval = [expireTime doubleValue];
            NSDate *expireDate = [NSDate dateWithTimeIntervalSince1970:expireTimeInterval];
            if ([currentDate compare:expireDate] != NSOrderedAscending) {
                // 当前时间等于或在过期时间之后 已经到了过期时间
                [self.aLiYunTokenManager loadData];

            } else {
                // 当前时间在过期时间之前 还没到过期时间
            }
        }else{
            [self.aLiYunTokenManager loadData];
        }
    }else{
        [self.aLiYunTokenManager loadData];
    }
}


#pragma mark - 更新错词数据
-(void)updateErrorWord{
    if(self.lastCourseTestModel.groupId){
        self.page = 1;
        [self.errorDataArr removeAllObjects];
        [self loadErrorData];
    }else{
        self.isUpdateErrorData = YES;
        [self checkData];
    }
}

#pragma mark - 获取课程数据
-(void)loadData{
    self.listManager.bookId = self.bookListModel.bookId;
    [self.listManager loadData];
}

#pragma mark - 获取单词数据
-(void)loadErrorData{
    self.wordListManager.type = @"2";
    self.wordListManager.groupId = self.lastCourseTestModel.groupId;
    self.wordListManager.bookId = self.bookListModel.bookId;
    self.wordListManager.page = [NSString stringWithFormat:@"%ld",self.page];
    [self.wordListManager loadData];
}

#pragma mark - 检查是否有上一次记录
-(void)checkData{
    self.isBack = NO;
    self.lastTestManager.bookId = self.bookListModel.bookId;
    [self.lastTestManager loadData];
}

#pragma mark - 保存测试设置
-(void)saveTestSetWithNumber:(NSString*)number andMode:(NSString*)mode{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    self.editUserInfoManager.userId = userId;
    self.editUserInfoManager.wordNumber = number;
    self.editUserInfoManager.mode = mode;
    [self.editUserInfoManager loadData];
}

#pragma mark - 不保留进度
-(void)deleteProgress{
    self.deleteProgressManager.groupId = self.lastCourseTestModel.groupId;
    [self.deleteProgressManager loadData];
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.customNavigationBar setTitle:[NSString stringWithFormat:@"%@ (%@)",self.bookListModel.name,self.bookListModel.volumeName]];
    UIButton *setBtn = [[UIButton alloc]init];
    [setBtn setImage:[UIImage imageNamed:@"mine_set_logo"] forState:UIControlStateNormal];
    [setBtn addTarget:self action:@selector(setBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:setBtn];
    [setBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(@34);
        make.right.mas_equalTo(@-11);
        make.bottom.mas_equalTo(@-5);
    }];
    
    self.courseBtn = [[UIButton alloc]init];
    self.courseBtn.titleLabel.font = JPUIFontPingFangSCRegular(15);
    [self.courseBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
    [self.courseBtn setTitleColor:KFontBlackColor forState:UIControlStateSelected];
    [self.courseBtn setTitle:@"课次" forState:UIControlStateNormal];
    [self.courseBtn addTarget:self action:@selector(courseBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.courseBtn];
    CGFloat cbtn_w = [self getStringWidthWithText:self.courseBtn.titleLabel.text font:self.courseBtn.titleLabel.font viewHeight:31];
    [self.courseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@6);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+7);
        make.height.mas_equalTo(@31);
        make.width.mas_equalTo(cbtn_w+20);
    }];
    self.courseBtn.selected = YES;
    
    self.errorBtn = [[UIButton alloc]init];
    self.errorBtn.titleLabel.font = JPUIFontPingFangSCRegular(15);
    [self.errorBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
    [self.errorBtn setTitleColor:KFontBlackColor forState:UIControlStateSelected];
    [self.errorBtn setTitle:@"错词(0)" forState:UIControlStateNormal];
    [self.errorBtn addTarget:self action:@selector(errorBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.errorBtn ];
    CGFloat ebtn_w = [self getStringWidthWithText:self.errorBtn.titleLabel.text font:self.errorBtn.titleLabel.font viewHeight:31];
    [self.errorBtn  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-6);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+7);
        make.height.mas_equalTo(@31);
        make.width.mas_equalTo(ebtn_w+20);
    }];
    
    //选课
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+37,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-37-83) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 46;
    [self.tableView registerClass:NSClassFromString(@"TestWordChooseCourseCell") forCellReuseIdentifier:@"TestWordChooseCourseCell"];
    [self.view addSubview:self.tableView];
    
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = KLineColor;
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(@0);
        make.bottom.mas_equalTo(-82);
        make.height.mas_equalTo(@1);
    }];
    
    self.allSelBtn = [[UIButton alloc]init];
    [self.allSelBtn setImage:[UIImage imageNamed:@"word_error_reason_unsel"] forState:UIControlStateNormal];
    [self.allSelBtn setImage:[UIImage imageNamed:@"word_error_reason_sel"] forState:UIControlStateSelected];
    [self.allSelBtn addTarget:self action:@selector(allSelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.allSelBtn.adjustsImageWhenHighlighted = NO;
    [self.allSelBtn setTitle:@"  全选" forState:UIControlStateNormal];
    [self.allSelBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
    self.allSelBtn.titleLabel.font = JPUIFontPingFangSCRegular(16);
    [self.view addSubview:self.allSelBtn];
    CGFloat a_w = [self getStringWidthWithText:self.allSelBtn.titleLabel.text font:self.allSelBtn.titleLabel.font viewHeight:32];
    [self.allSelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.height.mas_equalTo(@32);
        make.width.mas_equalTo(a_w+20);
        make.bottom.mas_equalTo(@-42);
    }];
    
    __weak typeof(self)weakSelf = self;
    self.sureBtn = [[UIButton alloc]init];
    self.sureBtn.backgroundColor = KThemeColor;
    self.sureBtn.layer.cornerRadius = 18;
    self.sureBtn.layer.masksToBounds = YES;
    [self.sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [self.sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.sureBtn.titleLabel.font = JPUIFontPingFangSCMedium(14);
    self.sureBtn.ym_acceptEventInterval = 2.0;
    [self.sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.sureBtn];
    [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-16);
        make.height.mas_equalTo(@36);
        make.centerY.mas_equalTo(weakSelf.allSelBtn);
        make.width.mas_equalTo(@88);
    }];
    
    
    //错词
    self.errorTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+37,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-37-83) style:UITableViewStylePlain];
    self.errorTableView.delegate = self;
    self.errorTableView.dataSource = self;
    self.errorTableView.backgroundColor = [UIColor whiteColor];
    self.errorTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.errorTableView.rowHeight = 90;
    [self.errorTableView registerClass:NSClassFromString(@"MyCollectionListCell") forCellReuseIdentifier:@"MyCollectionListCell"];
    [self.view addSubview:self.errorTableView];
    self.errorTableView.hidden = YES;
    
    self.errorTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.errorDataArr removeAllObjects];
        weakSelf.page = 1;
        [weakSelf loadErrorData];
    }];
    
    self.errorTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page++;
        [weakSelf loadErrorData];
    }];
    
    self.testBtn = [[UIButton alloc]init];
    self.testBtn.backgroundColor = KThemeColor;
    self.testBtn.layer.cornerRadius = 20;
    self.testBtn.layer.masksToBounds = YES;
    [self.testBtn setTitle:@"错词测试" forState:UIControlStateNormal];
    [self.testBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.testBtn.titleLabel.font = JPUIFontPingFangSCMedium(14);
    self.testBtn.ym_acceptEventInterval = 2.0;
    [self.testBtn addTarget:self action:@selector(testBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.testBtn];
    [self.testBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-16);
        make.height.mas_equalTo(@40);
        make.bottom.mas_equalTo(@-38);
        make.left.mas_equalTo(@16);
    }];
    self.testBtn.hidden = YES;
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    if (isIPAD) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            // 更新导航栏和背景视图的大小
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth, kYM_NAVIGATIONBAR_HEIGHT);
            self.tableView.frame= CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+37,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-37-83);
            [self.tableView reloadData];
            self.errorTableView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+37,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-37-83);
            [self.errorTableView reloadData];
            if(self.oldDataAlertView){
                self.oldDataAlertView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
            }
            if(self.saveAlertView){
                self.saveAlertView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
            }
            if(self.setView){
                self.setView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
            }
        });
    }
}


#pragma mark - 课次
-(void)courseBtnClick{
    self.courseBtn.selected = YES;
    self.errorBtn.selected = NO;
    self.tableView.hidden = NO;
    self.sureBtn.hidden = NO;
    self.allSelBtn.hidden = NO;
    self.errorTableView.hidden = YES;
    self.testBtn.hidden = YES;
    [self.customNavigationBar setTitle:[NSString stringWithFormat:@"%@ (%@)",self.bookListModel.name,self.bookListModel.volumeName]];
    
    //获取课程数据
    [self.dataArr removeAllObjects];
    [self loadData];
    
}

#pragma mark - 错词
-(void)errorBtnClick{
    [self.customNavigationBar setTitle:@""];
    self.courseBtn.selected = NO;
    self.errorBtn.selected = YES;
    self.tableView.hidden = YES;
    self.sureBtn.hidden = YES;
    self.allSelBtn.hidden = YES;
    self.errorTableView.hidden = NO;
    self.testBtn.hidden = NO;
    if(self.lastCourseTestModel){
        if(self.lastCourseTestModel.isHaveNext.integerValue == 1){
            [self.errorDataArr removeAllObjects];
            self.page = 1;
            //获取错词数据
            [self loadErrorData];
        }
    }
}

#pragma mark - 错词测试
-(void)testBtnClick{
    
    if(self.errorDataArr.count == 0){
        [JPProgressHUD showMsg:@"没有可测试的单词"];
        return;
    }
    
    TestWordViewController *vc = [[TestWordViewController alloc] init];
    vc.isError = YES;
    vc.bookId = self.bookListModel.bookId;
    vc.groupId = self.lastCourseTestModel.groupId;
    JPNavigationController *nav = [[JPNavigationController alloc]initWithRootViewController:vc];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:nav animated:YES completion:nil];
 
}

#pragma mark - 是否有历史数据弹窗
-(void)showOldDataAlertView{
    if(!self.oldDataAlertView){
        self.oldDataAlertView = [[WordTestOldDataAlertView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,self.currentAvailableHeight)];
    }
    if(KEY_WINDOW){
        self.oldDataAlertView.model = self.lastCourseTestModel;
        [KEY_WINDOW addSubview:self.oldDataAlertView];
        __weak typeof(self)weakSelf = self;
        [self.oldDataAlertView setClickBlock:^(BOOL isYes) {
            [weakSelf.oldDataAlertView removeFromSuperview];
            if(isYes == YES){
                TestWordViewController *vc = [[TestWordViewController alloc]init];
                vc.isError = NO;
                vc.bookId = weakSelf.bookListModel.bookId;
                vc.groupId = weakSelf.lastCourseTestModel.groupId;
                JPNavigationController *nav = [[JPNavigationController alloc]initWithRootViewController:vc];
                nav.modalPresentationStyle = UIModalPresentationFullScreen;
                [weakSelf presentViewController:nav animated:YES completion:nil];
            }else{
                [weakSelf.selArr removeAllObjects];
                [weakSelf.tableView reloadData];
            }
        }];
    }
}

#pragma mark - 设置
-(void)setBtnClick{
    NSString *wordNumber0 = [[NSUserDefaults standardUserDefaults]objectForKey:@"wordNumber"];
    if(!wordNumber0){
        wordNumber0 = @"10";
    }
    NSString *mode0 = [[NSUserDefaults standardUserDefaults]objectForKey:@"mode"];
    if(!mode0){
        mode0 = @"1,2,3";
    }
    
    if(!self.setView){
        self.setView = [[WordTestSetView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,self.currentAvailableHeight) andWordNumber:wordNumber0 andMode:mode0];
    }
    self.setView.wordNumber = wordNumber0;
    self.setView.mode = mode0;
    if(KEY_WINDOW){
        [KEY_WINDOW addSubview:self.setView];
        __weak typeof(self)weakSelf = self;
        [self.setView setSureBlock:^(NSString * _Nonnull wordNumber, NSString * _Nonnull mode) {
            [weakSelf.setView removeFromSuperview];
            [weakSelf saveTestSetWithNumber:wordNumber andMode:mode];
        }];
    }
}

#pragma mark - 全选
-(void)allSelBtnClick{
    self.allSelBtn.selected = !self.allSelBtn.selected;
    [self.selArr removeAllObjects];
    if(self.allSelBtn.selected == YES){
        for(NSInteger i = 0; i < self.dataArr.count;i++){
            CourseListModel *model = self.dataArr[i];
            [self.selArr addObject:model.courseId];
        }
    }
    [self.tableView reloadData];
}

#pragma mark - 确定
-(void)sureBtnClick{
    
    if(self.selArr.count == 0){
        [JPProgressHUD showMsg:@"请先选择课程"];
        return;
    }
    
    NSMutableArray *sortedSelArr = [NSMutableArray arrayWithArray:self.selArr];
    // 对数组进行排序
    [sortedSelArr sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
        NSInteger num1 = [str1 integerValue];
        NSInteger num2 = [str2 integerValue];
        if (num1 < num2) {
            return NSOrderedAscending;
        } else if (num1 > num2) {
            return NSOrderedDescending;
        } else {
            return NSOrderedSame;
        }
    }];
    
    // 拼接排序后的数组
    NSMutableString *cstr = [NSMutableString string];
    for (NSInteger i = 0; i < sortedSelArr.count; i++) {
        NSString *str = sortedSelArr[i];
        [cstr appendString:str];
        if (i < sortedSelArr.count - 1) {
            [cstr appendString:@","];
        }
    }
    
    self.chooseCourseManager.courseIds = cstr;
    self.chooseCourseManager.bookId = self.bookListModel.bookId;
    [self.chooseCourseManager loadData];
    
}

#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([tableView isEqual:self.tableView]){
        TestWordChooseCourseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TestWordChooseCourseCell"];
        if(indexPath.section < self.dataArr.count){
            CourseListModel *model = self.dataArr[indexPath.section];
            if([self.selArr containsObject:model.courseId]){
                cell.isSel = YES;
            }else{
                cell.isSel = NO;
            }
            cell.model = model;
        }
        return cell;
    }
    
    MyCollectionListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCollectionListCell"];
    if(indexPath.row < self.errorDataArr.count){
        cell.isSel = NO;
        WordListModel *model = self.errorDataArr[indexPath.row];
        cell.wordModel = model;
        __weak typeof(self)self_weak_ = self;
        __weak typeof(cell)cell_weak_ = cell;
        [cell setPlayBlock:^{
            //停止正在播放的
            [self_weak_ stopSpeaking];
            self_weak_.currentCell = cell_weak_;
            if(indexPath.row == self_weak_.playIndex){
                //暂停
                self_weak_.playIndex = -1;
            }else{
                //播放
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self_weak_.playIndex = indexPath.row;
                    if(model.audio&&![model.audio isEqualToString:@""]){
                        [self_weak_ playAudio:model.audio];
                    }else{
                        if((model.pronunciation)&&(![model.pronunciation isEqualToString:@""])){
                            if((model.writing)&&(model.isReadWriting)&&([model.isReadWriting isEqualToString:@"1"]||model.isReadWriting.integerValue == 1)){
                                [self_weak_ speakJapaneseText:model.writing];
                            }else{
                                [self_weak_ speakJapaneseText:model.pronunciation];
                            }
                        }else{
                            if((model.writing)&&(![model.writing isEqualToString:@""])){
                                [self_weak_ speakJapaneseText:model.writing];
                            }
                        }
                    }
                });
            }
        }];
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if([tableView isEqual:self.tableView]){
        return 1;
    }
    return self.errorDataArr.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if([tableView isEqual:self.tableView]){
        return self.dataArr.count;
    }
    return 1;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if([tableView isEqual:self.tableView]){
        UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,8)];
        headView.backgroundColor = [UIColor whiteColor];
        return headView;
    }
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,0.00000001)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if([tableView isEqual:self.tableView]){
        return 8;
    }
    return 0.00000001;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if([tableView isEqual:self.tableView]){
        UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,8)];
        footerView.backgroundColor = [UIColor whiteColor];
        return footerView;
    }
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,0.00000001)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if([tableView isEqual:self.tableView]){
        return 8;
    }
    return 0.00000001;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if([tableView isEqual:self.tableView]){
        if(indexPath.section < self.dataArr.count){
            CourseListModel *model = self.dataArr[indexPath.section];
            if([self.selArr containsObject:model.courseId]){
                [self.selArr removeObject:model.courseId];
            }else{
                [self.selArr addObject:model.courseId];
            }
            [self.tableView reloadData];
            if((self.selArr.count > 0)&&(self.selArr.count == self.dataArr.count)){
                self.allSelBtn.selected = YES;
            }else{
                self.allSelBtn.selected = NO;
            }
        }
    }
    
    if([tableView isEqual:self.errorTableView]){
        if(indexPath.row < self.errorDataArr.count){
            [self stopSpeaking];
            WordListModel *model = self.errorDataArr[indexPath.row];
            WordDetialViewController *vc = [[WordDetialViewController alloc]init];
            vc.wordModel = model;
            JPNavigationController *nav = [[JPNavigationController alloc]initWithRootViewController:vc];
            nav.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:nav animated:YES completion:nil];
        }
    }
    
}

#pragma mark - 播放读取文本
- (void)speakJapaneseText:(NSString *)text{
    
    [self listentTypeSet];
    
    if(self.currentCell){
        [self.currentCell startVoiceAnimation];
    }
//    if(!self.synthesizer){
//        self.synthesizer = [[AVSpeechSynthesizer alloc] init];
//        self.synthesizer.delegate = self;
//    }
//    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:text];
//    utterance.rate = 0.53; // 语速，范围0.0~1.0
//    utterance.pitchMultiplier = 1.1; // 音高，范围0.5~2.0
//    utterance.volume = 1.0; // 音量，范围0~1
//    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"ja-JP"];
//    utterance.voice = voice;
//    [self.synthesizer speakUtterance:utterance];
    
    
    dispatch_async(self.work_queue, ^{
        // 如果上个任务没有合成完毕，手动取消，开始合成新的任务
        [self.nui nui_tts_cancel:NULL];
        
        [self UpdateTtsParams:text];

        [self.nui nui_tts_play:"1" taskId:"" text:[text UTF8String]];
    });
    
}

#pragma mark - 更新语音合成参数配置
-(void)UpdateTtsParams:(NSString *)content{
    
    int chars = 0;
    // 支持一次性合成300字符以内的文字，其中1个汉字、1个英文字母或1个标点均算作1个字符，
    // 超过300个字符的内容将会截断。所以请确保传入的text小于300字符(不包含ssml格式)。
    // 长短文本语音合成收费不同，请注意。
    // 300字这个截点可能会变更，以官网文档为准。
    chars = [self.nui nui_tts_get_num_of_chars: [content UTF8String]];
    if (chars > 300) {
        // 超过300字符设置成 长文本语音合成 模式
        [self.nui nui_tts_set_param:"tts_version" value:"1"];
    } else {
        // 未超过300字符设置成 短文本语音合成 模式
        [self.nui nui_tts_set_param:"tts_version" value:"0"];
    }
}

#pragma mark - tts callback
- (void)onNuiTtsEventCallback:(NuiSdkTtsEvent)event taskId:(char*)taskid code:(int)code{
//    TLog(@"onNuiTtsEventCallback event[%d]", event);
    if (event == TTS_EVENT_START) {
//        TLog(@"onNuiTtsEventCallback TTS_EVENT_START");
        // 启动播放器
        [self.audioController startPlayer];
    } else if (event == TTS_EVENT_END || event == TTS_EVENT_CANCEL || event == TTS_EVENT_ERROR) {
        if (event == TTS_EVENT_END) {
//            TLog(@"onNuiTtsEventCallback TTS_EVENT_END");
            // 注意这里的event事件是指语音合成完成，而非播放完成，播放完成需要由audioController对象来进行通知
            [self.audioController drain];
        } else {
            // 取消播报、或者发生异常时终止播放
            if(self.audioController){
                [self.audioController stopPlayer];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if(self.currentCell){
                    [self.currentCell stopVoiceAnimation];
                }
                self.playIndex =  -1;
            });
        }
        if (event == TTS_EVENT_ERROR) {
            const char *errmsg = [self.nui nui_tts_get_param: "error_msg"];
//            TLog(@"tts get errmsg:%s", errmsg);
            NSString *errorString = [NSString stringWithUTF8String:errmsg];
            if ([errorString containsString:@"144003"]) {
               //token过期
                [self.aLiYunTokenManager loadData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成token过期，已重新获取，请再次点击播放"];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [JPProgressHUD showWrongMsg:@"语音合成失败"];
                });
            }
        }
      
    }
}

- (void)onNuiTtsUserdataCallback:(char*)info infoLen:(int)info_len buffer:(char*)buffer len:(int)len taskId:(char*)task_id {
    TLog(@"onNuiTtsUserdataCallback info ...");
    if (info_len > 0) {
        TLog(@"onNuiTtsUserdataCallback info text %s. index %d.", info, info_len);
    }
    if (len > 0) {
        [self.audioController write:(char*)buffer Length:(unsigned int)len];
    }
}

-(void)onNuiTtsVolumeCallback:(int)volume taskId:(char*)task_id{
    
}

#pragma mark - Audio Player Delegate
-(void)playerDidFinish {
    //播放数据被实际播放完成后回调。
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.currentCell){
            [self.currentCell stopVoiceAnimation];
        }
        self.playIndex =  -1;
    });
}

//语音合成完成
-(void)playerDrainDataFinish{
   
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.audioController.isPlayerStopped == YES){
            if(self.currentCell){
                [self.currentCell stopVoiceAnimation];
            }
            self.playIndex =  -1;
        }
    });

}

#pragma mark - 停止当前正在读的文本
- (void)stopSpeaking{
//    if (self.synthesizer&&self.synthesizer.isSpeaking) {
//        [self.synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
//        if(self.currentCell){
//            [self.currentCell stopVoiceAnimation];
//        }
//    }
    
    if(self.work_queue){
        dispatch_async(self.work_queue, ^{
            // 如果上个任务没有合成完毕，手动取消
            if(self.nui){
                [self.nui nui_tts_cancel:NULL];
            }
        });
    }
    if(self.audioController){
        [self.audioController stopPlayer];
    }
    if(self.currentCell){
        [self.currentCell stopVoiceAnimation];
    }
    
    if(self.avPlayer){
        self.isPlaying = NO;
        [self.avPlayer pause];
        [self.avPlayer seekToTime:kCMTimeZero];
    }
    
}

#pragma mark - 单词音频播放
-(void)playAudio:(NSString *)audio{
    
    [self listentTypeSet];
    
    if(self.currentCell){
        [self.currentCell startVoiceAnimation];
    }
    
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:audio]];
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    if(self.avPlayer){
        [self.avPlayer pause];
        [self.avPlayer replaceCurrentItemWithPlayerItem:item];
    }else{
        self.avPlayer = [[AVPlayer alloc] initWithPlayerItem:item];
    }
    [self.avPlayer play];
    self.isPlaying = YES;
}

-(void)playToEndTime:(NSNotification*)notifi{
    if(self.currentCell){
        [self.currentCell stopVoiceAnimation];
    }
    self.playIndex =  -1;
    [self.avPlayer seekToTime:kCMTimeZero];
    self.isPlaying = NO;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey] integerValue];
        if (status == AVPlayerItemStatusReadyToPlay) {
            NSLog(@"播放成功");
            
        } else if (status == AVPlayerItemStatusFailed) {
            NSLog(@"播放失败");
            [JPProgressHUD showMsg:@"播放失败"];
            if(self.currentCell){
                [self.currentCell stopVoiceAnimation];
            }
            self.playIndex =  -1;
        }
    }
}

//#pragma mark - AVSpeechSynthesizer deletage
//- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance{
//    // 当前文本已经读完
//    if(self.currentCell){
//        [self.currentCell stopVoiceAnimation];
//    }
//    self.playIndex =  -1;
//}

#pragma mark - 设置静音模式下也能播放音频
-(void)listentTypeSet{
    // 获取当前的音频会话类别
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    // 检查当前类别是否已经是 AVAudioSessionCategoryPlayback
    if (![audioSession.category isEqualToString:AVAudioSessionCategoryPlayback]) {
        NSError *setCategoryError = nil;
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
        
        if (setCategoryError) {
            NSLog(@"Error setting category: %@", [setCategoryError localizedDescription]);
        }
    }
    
    // 检查音频会话是否已经处于激活状态
    if (!audioSession.isOtherAudioPlaying) {
        NSError *activationError = nil;
        [audioSession setActive:YES error:&activationError];
        
        if (activationError) {
            NSLog(@"Error activating session: %@", [activationError localizedDescription]);
        }
    }
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.listManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [CourseListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.dataArr = [NSMutableArray arrayWithArray:arr];
        [self.tableView reloadData];
    }
    
    if([manager isEqual:self.lastTestManager]){
        NSDictionary *dic = manager.response.content;
        self.lastCourseTestModel = [LastCourseTestModel mj_objectWithKeyValues:dic[@"data"]];
        if(self.isUpdateErrorData == YES){
            self.isUpdateErrorData = NO;
            if(self.lastCourseTestModel.isHaveNext.integerValue == 1){
                //获取错词数据
                self.page = 1;
                [self.errorDataArr removeAllObjects];
                [self loadErrorData];
            }
        }else{
            if(self.isFirst == YES){
                self.isFirst = NO;
                if(self.lastCourseTestModel.isHaveNext.integerValue == 1){
                    self.page = 1;
                    [self.errorDataArr removeAllObjects];
                    //获取错词数据
                    [self loadErrorData];
                }
            }
            if(self.lastCourseTestModel.isHaveNext.integerValue == 1){
                NSArray *courseList = [CourseListModel mj_objectArrayWithKeyValuesArray:self.lastCourseTestModel.courseList];
                NSMutableString *namestr = [NSMutableString string];
                for(NSInteger i = 0;i < courseList.count;i++){
                    CourseListModel *courseModel = courseList[i];
                    [self.selArr addObject:courseModel.courseId];
                    [namestr appendString:courseModel.name];
                    if(i < courseList.count-1){
                        [namestr appendString:@"、"];
                    }
                }
                self.lastCourseTestModel.courseName = namestr;
                if(self.isBack == YES){
                    self.isBack = NO;
                    [self showSaveAlertView];
                }else{
                    [self.tableView reloadData];
                    [self showOldDataAlertView];
                }
            }else{
                if(self.isBack == YES){
                    self.isBack = NO;
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }
        }
    }
    
    if([manager isEqual:self.editUserInfoManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        NSString *wordNumber = [NSString stringWithFormat:@"%@",dic[@"data"][@"wordNumber"]];
        NSString *mode = [NSString stringWithFormat:@"%@",dic[@"data"][@"mode"]];
        if(wordNumber){
            [[NSUserDefaults standardUserDefaults]setObject:wordNumber forKey:@"wordNumber"];
        }
        if(mode){
            [[NSUserDefaults standardUserDefaults]setObject:mode forKey:@"mode"];
        }
    }
    
    if([manager isEqual:self.chooseCourseManager]){
        NSDictionary *dic = manager.response.content;
        NSString *groupId = [NSString stringWithFormat:@"%@",dic[@"data"][@"testGroup"][@"groupId"]];
        NSArray *courseList = [CourseListModel mj_objectArrayWithKeyValuesArray:dic[@"data"][@"courseList"]];
        NSMutableString *namestr = [NSMutableString string];
        for(NSInteger i = 0;i < courseList.count;i++){
            CourseListModel *model = courseList[i];
            [namestr appendString:model.name];
            if(i < courseList.count-1){
                [namestr appendString:@","];
            }
        }
        CourseChooseFinishViewController *vc = [[CourseChooseFinishViewController alloc]init];
        vc.bookId = self.bookListModel.bookId;
        vc.groupId = groupId;
        vc.courseName = namestr;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
    if([manager isEqual:self.wordListManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [WordListModel mj_objectArrayWithKeyValuesArray:dic[@"data"][@"list"]];
        if(self.page == 1){
            self.errorDataArr = [NSMutableArray arrayWithArray:arr];
        }else{
            [self.errorDataArr addObjectsFromArray:arr];
        }
        [self.errorTableView reloadData];
        NSString *count = [NSString stringWithFormat:@"%@",dic[@"data"][@"count"]];
        [self.errorTableView.mj_header endRefreshing];
        if(self.errorDataArr.count == count.integerValue){
            [self.errorTableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.errorTableView.mj_footer endRefreshing];
        }
        if(self.page == 1){
            [self.errorBtn setTitle:[NSString stringWithFormat:@"错词(%@)",count] forState:UIControlStateNormal];
            CGFloat ebtn_w = [self getStringWidthWithText:self.errorBtn.titleLabel.text font:self.errorBtn.titleLabel.font viewHeight:31];
            [self.errorBtn mas_updateConstraints:^(MASConstraintMaker *make){
                make.width.mas_equalTo(ebtn_w+20);
            }];
        }
    }
    
    if([manager isEqual:self.deleteProgressManager]){
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
    if([manager isEqual:self.aLiYunTokenManager]){
         NSDictionary *dic = manager.response.content;
         if(dic[@"data"][@"token"]){
             NSString *token = [NSString stringWithFormat:@"%@",dic[@"data"][@"token"]];
             [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"ALIYUN_YUYIN_TOKEN"];
         }
         if(dic[@"data"][@"expireTime"]){
             NSString *expireTime = [NSString stringWithFormat:@"%@",dic[@"data"][@"expireTime"]];
             [[NSUserDefaults standardUserDefaults]setObject:expireTime forKey:@"ALIYUN_YUYIN_EXPIRETIME"];
         }
        if (self.nui) {
           [self.nui nui_tts_release];
           self.nui = nil;
        }
        [self NuiTtsInit];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.lastTestManager]){
        if(self.isBack == YES){
            self.isBack = NO;
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    if([manager isEqual:self.deleteProgressManager]){
        [self.navigationController popViewControllerAnimated:YES];
    }
    if([manager isEqual:self.wordListManager]){
        [self.errorTableView reloadData];
        [self.errorTableView.mj_header endRefreshing];
        [self.errorTableView.mj_footer endRefreshing];
    }
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


-(void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    // 若_nui未进行释放, 下次进入此view使用的_nui处于已初始化,
    // 则再调用nui_tts_initialize无法覆盖已经设置的参数.
    if(self.audioController){
        [self.audioController cleanPlayerBuffer];
    }
    
    if(self.avPlayer&&self.isPlaying == YES){
        [self.avPlayer pause];
        self.isPlaying = NO;
    }
}

@end
